package com.gpjcjl.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.Constants;
import android.device.scanner.configuration.PropertyID;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.ViewModelProvider;

import com.base.lib.IntentUtil;
import com.base.lib.ToastUtil;
import com.gpjcjl.BaseActivity;
import com.gpjcjl.R;
import com.gpjcjl.entity.RecordDetail;
import com.gpjcjl.event.RecordDetailUpdate;
import com.gpjcjl.util.DataProvider;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 气瓶信息编辑页面
 */
public class RecordDetailEditActivity extends BaseActivity {

    private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action

    @BindView(R.id.edit_check_num)
    EditText editCheckNum;
    @BindView(R.id.tv_produce)
    TextView tvProduce;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.edit_num)
    EditText editNum;
    @BindView(R.id.edit_qrcode)
    EditText editQrCode;

    @BindView(R.id.edit_wall)
    EditText editWall;
    @BindView(R.id.edit_weight)
    EditText editWeight;

    @BindView(R.id.tv_around)
    TextView tvAround;
    @BindView(R.id.tv_bottle)
    TextView tvBottle;
    @BindView(R.id.tv_water)
    TextView tvWater;
    @BindView(R.id.tv_airtight)
    TextView tvAirtight;
    @BindView(R.id.edit_epilog)
    EditText editEpilog;
    @BindView(R.id.edit_scrap)
    EditText editScrap;

    private RecordDetailViewModel viewModel;
    private RecordDetail detail;
    private boolean isRemote;

    private ScanManager mScanManager;
    private final BroadcastReceiver mScanReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            if (temp == Constants.Symbology.QRCODE) {
                byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
                int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
                String barcodeStr = new String(barcode, 0, barcodelen);
                searchByQrCode(barcodeStr);
            }
        }
    };

    private void searchByQrCode(String barcodeStr) {
        showLoading();
        viewModel.scan(barcodeStr).observe(RecordDetailEditActivity.this, result -> {
            dismissLoading();
            ToastUtil.showToast(mContext, result.getMsg());
            RecordDetail data = result.getData();
            if (result.isSuccess() && data != null) {
                editNum.setText(data.getNum());
                tvProduce.setText(data.getProduce());
                tvDate.setText(data.getProduce_time());
                editQrCode.setText(data.getNumber());
            }
        });
    }

    public static void startIntent(Context context, RecordDetail recordDetail, boolean isRemote) {
        Intent it = new Intent(context, RecordDetailEditActivity.class);
        it.putExtra("detail", recordDetail);
        it.putExtra("isRemote", isRemote);
        context.startActivity(it);
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            IntentFilter filter = new IntentFilter();
            int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
            String[] value_buf = mScanManager.getParameterString(idbuf);
            if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
                filter.addAction(value_buf[0]);
            } else {
                filter.addAction(SCAN_ACTION);
            }
            registerReceiver(mScanReceiver, filter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            unregisterReceiver(mScanReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_record_detail_edit;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(RecordDetailViewModel.class);
        detail = getIntent().getExtras().getParcelable("detail");
        isRemote = getIntent().getBooleanExtra("isRemote", false);
        initData();
        try {
            mScanManager = new ScanManager();
            mScanManager.switchOutputMode(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initData() {
        editCheckNum.setText(detail.getCheck_num());
        tvProduce.setText(detail.getProduce());
        tvDate.setText(detail.getProduce_time());
        editNum.setText(detail.getNum());
        editQrCode.setText(detail.getQrCode());

        editWall.setText(detail.getWall());
        editWeight.setText(detail.getWeight());

        tvAround.setText(detail.getAround());
        tvBottle.setText(detail.getBottle());
        tvWater.setText(detail.getWater_gage());
        tvAirtight.setText(detail.getAirtight());

        editEpilog.setText(detail.getEpilog());
        editScrap.setText(detail.getScrap());
    }

    @OnClick({R.id.tvSetting, R.id.tv_date, R.id.tv_produce, R.id.btn_save, R.id.iv_add
            , R.id.tv_around, R.id.tv_bottle, R.id.tv_water, R.id.tv_airtight})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvSetting:
                IntentUtil.startIntent(mContext, SettingActivity.class);
                break;
            case R.id.btn_save:
                editRecordDetail();
                break;
            case R.id.tv_date:
                showDatePicker();
                break;
            case R.id.tv_produce:
            case R.id.iv_add:
                ProduceListActivity.startIntentForResult(this, 1);
                break;
            case R.id.tv_around:
                showTypeDialog(tvAround);
                break;
            case R.id.tv_bottle:
                showTypeDialog(tvBottle);
                break;
            case R.id.tv_water:
                showTypeDialog(tvWater);
                break;
            case R.id.tv_airtight:
                showTypeDialog(tvAirtight);
                break;
            default:
                break;
        }
    }

    private void editRecordDetail() {
        String checkNum = editCheckNum.getText().toString().trim();
        String produce = tvProduce.getText().toString().trim();
        String produceTime = tvDate.getText().toString().trim();
        String num = editNum.getText().toString().trim();
        String qrCode = editQrCode.getText().toString().trim();

        String wall = editWall.getText().toString().trim();
        String weight = editWeight.getText().toString().trim();

        String around = tvAround.getText().toString().trim();
        String bottle = tvBottle.getText().toString().trim();
        String water = tvWater.getText().toString().trim();
        String airtight = tvAirtight.getText().toString().trim();

        String epilog = editEpilog.getText().toString().trim();
        String scrap = editScrap.getText().toString().trim();

        if (TextUtils.isEmpty(checkNum)) {
            ToastUtil.showToast(mContext, "请输入检验编号");
        } else if (TextUtils.isEmpty(produce)) {
            ToastUtil.showToast(mContext, "请选择制造单位");
        } else if (TextUtils.isEmpty(produceTime)) {
            ToastUtil.showToast(mContext, "请选择制造日期");
        } else if (TextUtils.isEmpty(num)) {
            ToastUtil.showToast(mContext, "请输入钢瓶编号");
        } else if (TextUtils.isEmpty(wall)) {
            ToastUtil.showToast(mContext, "请输入实测壁厚");
        } else {
            detail.setCheck_num(checkNum);
            detail.setProduce(produce);
            detail.setProduce_time(produceTime);
            detail.setNum(num);
            detail.setQrCode(qrCode);
            detail.setAround(around);
            detail.setWall(wall);
            detail.setWeight(weight);
            detail.setBottle(bottle);
            detail.setWater_gage(water);
            detail.setAirtight(airtight);
            detail.setEpilog(epilog);
            detail.setScrap(scrap);

            viewModel.editRecordDetail(isRemote, detail).observe(this, result -> {
                ToastUtil.showToast(mContext, result.getMsg());
                if (result.isSuccess()) {
                    EventBus.getDefault().post(new RecordDetailUpdate());
                    finish();
                }
            });
        }
    }

    private void showTypeDialog(TextView textView) {
        String[] items = DataProvider.getExpResult().toArray(new String[0]);
        new QMUIDialog.MenuDialogBuilder(mContext).addItems(items, (dialog, which) -> {
            textView.setText(items[which]);
            dialog.dismiss();
        }).show();
    }

    private void showDatePicker() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        View view = getLayoutInflater().inflate(R.layout.dialog_datepicker, null);
        DatePicker datePicker = view.findViewById(R.id.date_picker);
        //设置日期简略显示 否则详细显示 包括:星期\周
        datePicker.setCalendarViewShown(false);
        try {
            LinearLayout ll = (LinearLayout) datePicker.getChildAt(0);
            LinearLayout ll2 = (LinearLayout) ll.getChildAt(0);
            ll2.getChildAt(2).setVisibility(View.GONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置date布局
        builder.setView(view)
                .setTitle("选择日期")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", (dialog, which) -> {
                    //日期格式
                    int year = datePicker.getYear();
                    int month = datePicker.getMonth() + 1;
                    //                    int dayOfMonth = datePicker.getDayOfMonth();
                    tvDate.setText(String.format("%d-%d", year, month));
                    dialog.cancel();
                })
                .create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (1 == requestCode && data != null && data.hasExtra("result")) {
            String result = data.getStringExtra("result");
            tvProduce.setText(result);
        }
    }
}
